<template>
  <div v-loading="loading" style="width:100%;height:100%;">
    <iframe
      ref="searchView"
      :src="path"
      width="100%"
      height="100%"
      frameborder="0"
      style="margin:0px;"
      element-loading-text="加载中"
    ></iframe>
  </div>
</template>

<script>
export default {
  name: "aiSearch",
  data() {
    return { iframe: null, loading: false };
  },
  computed: {
    path() {
      // return "http://localhost:29671";
      return window.ENV.API_JZF;
    }
  },
  mounted() {
    this.iframe = this.$refs.searchView;
    this.addTokenHandel();
  },
  methods: {
    addTokenHandel() {
      this.loading = true;
      window.addEventListener("message", this.handleMessage);
      // 处理兼容行问题
      if (this.iframe.attachEvent) {
        this.iframe.attachEvent("onload", () => {
          this.onload();
        });
      } else {
        this.iframe.onload = this.onload;
      }
    },
    onload() {
      const loginInfo = localStorage.getItem("loginInfo");
      this.iframe.contentWindow.postMessage({ loginInfo: loginInfo }, "*");
      this.$store.commit("setIfrmaeSign", true);
      this.loading = false;
      console.log("iframe已加载完毕");
    },
    handleMessage(event) {
      const data = event.data;

      // 子页面调用更新密码
      if (data === "updatePassword") {
        this.$emit("updatePassword");
        return;
      }

      if (data.tokenError) {
        const map = {
          token: "",
          userInfo: {
            userId: "",
            userName: "",
            cnName: "",
            idCardNumber: "",
            departmentName: ""
          }
        };
        localStorage.setItem("loginInfo", JSON.stringify(map));
        localStorage.setItem("token", "");
        this.$store.commit("SET_TOKEN", "");
        this.$store.commit("SET_TOKEN", "");
        this.$store.commit("SET_USERINFO", "");
        this.$router.push("/login");
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
